//******************************************************************************/
//	
//		 AMETHYST Interface
//		-------------------
//	The module contains the AMETHYST interface Definitions.
//	
//		25/12/2011 - Rami Raviv - Module creation.
//              16/01/2012   VER 0.01 To MARIS
//              17/01/2012   VER 0.02 
//
//******************************************************************************

#ifndef AMETHYST_INTERFACE_H
#define AMETHYST_INTERFACE_H

#pragma pack(1)
//#pragma pack(1)

// int8 definitions. 
#define uint8 unsigned char
#define int8 char
#define sint8 signed char
//
// int16 definitions.
#define uint16 unsigned short
#define int16 short
#define sint16 signed short
// int32 definitions. 
#define uint32 unsigned long
#define int32 long
#define sint32 signed long
//
#define i6Q2 int8
#define i4Q4 int8
#define u6Q2 uint8
#define u4Q4 uint8
//
#define uint64 unsigned long long
#define int64 long long
#define sint64 signed long long
typedef uint16 TypeTBD_T; //type not defined yet
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

#define PRINTF printf
//
//
#define PAIF_DELIMITER (0x00D7)
#define PAIF_DELIMITER_MSB (0x00)
#define PAIF_DELIMITER_LSB (0xD7)


#define DELIMITER_SIZE sizeof(uint16)
#ifndef PEARL_INPUT_BUFFER_SIZE
#define PEARL_INPUT_BUFFER_SIZE			128
#endif
/* Number of output buffers. */
#define PEARL_NUMBER_OF_OUTPUT_BUFFERS	5
/* Output buffer size. */
#ifndef PEARL_OUTPUT_BUFFER_SIZE
#define PEARL_OUTPUT_BUFFER_SIZE		120
#endif

//
// Maximum message size in bytes  
//
#define MAX_PAIF_MESSAGE_SIZE (PEARL_OUTPUT_BUFFER_SIZE-DELIMITER_SIZE-1) //117  


//
//AMETHYST Parameters
//
//Hunting parameters (details are TBD depending on VMD)
//
#define AMETHPAR_HUNT_LearningPeriodDuration (0)               //Learning period length 0-255 seconds . Default 2
// Image area is divided to 256 blocks (16 in each axis). The LU and RB coordinates are describing the x, y of the blocks (each represented by 4 bits in range of 0-15).
// Successive Trigger/Mask area parameters should be added in the Amethyst. 
// They will be cleared upon reception of an FFFF value. A get command will give back the values added in the last set command
#define AMETHPAR_HUNT_TriggerArea (1)                         // LU-x, LU-y, RB-x, RB-y. Default 0,0,15,15 (0x00FF)
#define AMETHPAR_HUNT_MaskArea (2)                            //Same as Trigger area
#define AMETHPAR_HUNT_MinimalTimeTillEventDeclaration (3)     //
#define AMETHPAR_HUNT_StaticEventTime (4)                     //Events are marked as static after this time of inactivity (marked as "static alerts" in the WEM)
#define AMETHPAR_HUNT_CloseEventTime (5)                      //Event are closed after this time after becoming "static"
#define AMETHPAR_HUNT_MaskingMode (6)                         // 0 - disabled 1 - default/touch 2 - strong/cross
#define AMETHPAR_HUNT_TriggerMode (7)                         //0 - touch 1 - cross
#define AMETHPAR_HUNT_Direction (8)                          //0 - All 1 - Right only 2 - Left only
//0 - disable background motion filter
//XY - range of X to Y (decimal value)
//e.g. (12 - lowest to low, 24 - low to strong
#define AMETHPAR_HUNT_BackgroundMotionRange (9)              
#define AMETHPAR_HUNT_TreeBranchesFiltering (10)             //0 - disable 1 - low 2 - medium 3 - strong
#define AMETHPAR_HUNT_RainFilter (11)                        //0 - disable 1 - enabled
//Each value operates a predetermined combination of filter values. 
//Setting this parameter will override setting of the previous filter parameters. 
//If this parameters has not been "set" the answer value for a "get" will be 0xFFFF
#define AMETHPAR_HUNT_FilterPresent (12)                     //
// Minimal size of movement to consider as a detection at the bottom of the image - X
#define AMETHPAR_HUNT_DepthBottomX (13)
// Minimal size of movement to consider as a detection at the bottom of the image - Y
#define AMETHPAR_HUNT_DepthBottomY (14)
// Minimal size of movement to consider as a detection at the top (below the skyline) of the image - X
#define AMETHPAR_HUNT_DepthTopX (15)
// Minimal size of movement to consider as a detection at the top (below the skyline) of the image - Y
#define AMETHPAR_HUNT_DepthTopY (16)
// Amount of pixels in the top of the image which are masked from the detection algorithm
#define AMETHPAR_HUNT_DepthSkyline (17)
//Reserve
#define AMETHPAR_HUNT_Reserve2 (18)
#define AMETHPAR_HUNT_Reserve1 (19)
//
//Image/File parameters
//
#define AMETHPAR_IMG_BufferManagementMode (20)               //0 - cyclic 1 - non-cyclic (stop capturing when full). Default non-cyclic (1)
// Number of pixels to add around the detection when cropping detection only. Activated upon request in "get image slice"
#define AMETHPAR_IMG_FrameWidth (21)                         // 0-255. Default 0.
#define AMETHPAR_IMG_TimeBetweenSavedImages (22)             //0-255 [100 milliseconds]. Default 10 (= 1 fps)
#define AMETHPAR_IMG_ImageJPEGCompressionQualityFactor (23)  //20-95. Defalut 60
#define AMETHPAR_IMG_SliceSize (24)	                              //1-255 [bytes]	106	Size in bytes of the slices the image file is chopped into when transferring out to the Pearl upon request
#define AMETHPAR_IMG_MaxNumberOfImagesToKeepInBufferPerEvent (25)//	0-65535	1000	more than enough (indicates a 1000 seconds event which is too long)
#define AMETHPAR_IMG_NumberOfFramesToPutInThumbnailMovieClip (26)// 0-255	8	
//The saved file has to hold the header anyway. This parameter only effects where the first slice begins
#define AMETHPAR_IMG_IncludeJPEGFileHeaderWhenSendingTheFile (27)//0 - do not include header 1 - include header. Default 1-include Header
#define AMETHPAR_IMG_OverlapSize (28)                             //0-255 [bytes] number of bytes of overlap between each two adjacent slices. Default 0	
#define AMETHPAR_IMG_ShowAlertBox (29)                           //0 - do not display a red alert box in the image file 1 - display red alert box around the detection. Default 1.
#define AMETHPAR_IMG_AutomaticFileSizeThreshold (30)             //0-65535 Max Number of pixels in image type 3. Default 15000
#define AMETHPAR_IMG_Reserve4 (31)
#define AMETHPAR_IMG_Reserve3 (32)
#define AMETHPAR_IMG_Reserve2 (33)
#define AMETHPAR_IMG_Reserve1 (34)
//
//System parameters
//
//Indication how long before capture to change the GPIO [msec] (indication to the pearl)
#define AMETHPAR_SYS_TimeBeforeCapture (35)
#define AMETHPAR_SYS_Reserve4 (36)
#define AMETHPAR_SYS_Reserve3 (37)
#define AMETHPAR_SYS_Reserve2 (38)
#define AMETHPAR_SYS_Reserve1 (39)
//
#define AMETHPAR_MAX (40) //Maximum number of parameters
//

//
typedef uint8 AMETHPARId;
//
// Parameters 
//
typedef struct AMETHPARDesc
{
  AMETHPARId Id;
  uint8 destBitmask;   //bit 0 ram, bit  1-flash
} AMETHPARDescT;
//
typedef struct AMETHPARPair
{
  AMETHPARDescT paramDesc;
  uint16 paramVal;
} AMETHPARPairT;
//
typedef struct AMETHPARPairAns
{
  AMETHPARDescT paramDesc;
  uint16 paramValRam;
  uint16 paramValFlash;
} AMETHPARPairAnsT;
//
#define MAX_AMETHPAR_IN_MSG (MAX_PAIF_MESSAGE_SIZE-sizeof(PMIFMsgHeaderT)-sizeof(PMIFMsgFooterT)-1)/sizeof(AMETHPARPairT)


//#define MAX_REPLAY_PARAMS_IN_MSG (MAX_MESSAGE_SIZE-sizeof(PMIFMsgHeaderT)-sizeof(PMIFMsgFooterT)-1)/sizeof(paramPairAnsT)
//



//
//END AMETHYST Parameters
//
typedef uint64 TbdT;
//Time since 1.1.1970 milliseconds in 8 bytes
typedef uint64 AMETHTimeT;
typedef uint8 AMETHLearningPeriodDurationT;               //Learning period length 0-255 seconds . Default 2
// Image area is divided to 256 blocks (16 in each axis). The LU and RB coordinates are describing the x, y of the blocks (each represented by 4 bits in range of 0-15).
// Successive Trigger/Mask area parameters should be added in the Amethyst. 
// They will be cleared upon reception of an FFFF value. A get command will give back the values added in the last set command
typedef struct AMETHPoint
{
  uint16 X;
  uint16 Y;
} AMETHPointT;
//
typedef struct AMETHArea 
{
  uint16 LUx:4;
  uint16 LUy:4;
  uint16 RBx:4;
  uint16 RBy:4;
} AMETHAreaT;                       // LU-x, LU-y, RB-x, RB-y. Default 0,0,15,15 (0x00FF)
//
typedef enum AMETHYesNo
{
  No=0,
  Yes=1
} AMETHYesNoE;

//
typedef enum AMETHBufferManagementMode
{ 
  CYCLIC=0,    //cyclic
  NON_CYCLIC=1 // non-cyclic (stop capturing when full)
} AMETHBufferManagementModeE;
//
typedef enum AMETHStartStop
{ 
  Stop=0,    //Stop Operation
  Start=1 // Start Operation
} AMETHStartStopE;

typedef enum AMETHImageColor
{ 
   COLOR=0,  // Color
   BW=1    //Black & White
     

} AMETHImageColorE;
//
typedef enum AMETHIncludeHeader
{ 
  DoNotIncludeHeader=0,    
  IncludeHeader=1 
} AMETHIncludeHeaderE;
//
typedef enum AMETHShowAlertBox
{ 
  DoNotDisplayAlert=0,    
  DisplayAlert=1 
} AMETHShowAlertBoxE;
//
//File Formats
//
typedef enum AMETHFileFormatType
{
  VGA=0,
  QVGA,
  QQVGA,
  Thumbnail,
  ThumbnailMovie,
  Automatic
}AMETHFileFormatTypeE;
//
typedef enum AMETHCropE
{ 
  FULL=0,    
  CROPPED=1  
} AMETHCropE;
//
typedef enum AMETHImageType
{ 
  Alert=0,    //Alert
  Requested=1  // upon request
} AMETHImageTypeE;
//
typedef enum AMETHImageCompressionType
{ 
  JPEG=0,    
  OTHER
} AMETHImageCompressionTypeE;
//
//typedef struct AMETHZones
//{
//  uint16 zone[32]; //may be uint32 zone[16] //tbd
//};

typedef struct AMETHFileMetadata
{
    uint16 sensorID; //ID of the Camera
    AMETHTimeT timeOfDay; // time of day in TBD format based on Pearl time UINT 64 - counter since 01/01/1970 ; units  1/(2^15) of sec
    AMETHImageTypeE imageType; //Alert/requested picture 
    uint16 eventNumber;	
    uint16 fileNumber;
    AMETHCropE cropType;	//Full / cropped
    AMETHLearningPeriodDurationT learningPeriodLength;
    
    //It is not clear yet how to handle it
    // AMETHZonesT zone property TBD
    AMETHAreaT requestedTriggerArea; //TBD
    AMETHAreaT requestedTriggerAreaMask; //TBD 
    TbdT  MovementDetectionRules; //TBD
    
    AMETHFileFormatTypeE imageResolution; //(VGA/QVGA/QQVGA)
    AMETHImageColorE imageColor; 	//(color / BW)
    AMETHImageCompressionTypeE imageCompressionType; 	//(JPEG)
    uint8 imageQualityFactor; //	0-100%
    AMETHPointT detectionFrameBounderiesUpperLeft; //	Boundaries of the area where movement was detected - Left, Up, Right, Bottom (ALSO marked in the image itself)
    AMETHPointT detectionFrameBounderiesBottomRight;
    AMETHPointT DetectionCenterOfMass;//	X, Y
}AMETHFileMetadataT;
//
typedef uint8 PMIFMsgLengthT;
//
typedef uint8 PMIFMsgTypeE;
//
typedef struct PMIFMsgHeader
{
    PMIFMsgLengthT msgLength;
    PMIFMsgTypeE msgType;
    uint16 commandSequenceNumber; //Messages sequence number
} PMIFMsgHeaderT;
//
//
//CRC TYPE
//
#define CRC_T uint16
//typedef uint16 CRC_T;   //1- CCITT  CRC  calculated from after the "message length" to the last byte (including)
//
typedef struct PMIFMsgFooter
{
  CRC_T crc; 
} PMIFMsgFooterT;  
//
// Messages types definitions
//
// PEARL to AMETHYST
#define  PMIFRequestStatusMsgType (0)             // Request a status report (includes hunting alerts)
#define  PMIFRequestSetParameterMsgType (1)       // Set parameters for the WEM operation
#define  PMIFRequestGetParameterMsgType (2)       // Get the value currently set to a parameter
#define  PMIFRequestHuntingModeMsgType (3)        // Request the Amethyst to start/stop hunting for movement using the current parameters
#define  PMIFRequestImageCaptureMsgType (4)       // Request the Amethyst to take a snapshot at requested time of day or a series of times using the current parameters
#define  PMIFRequestEventInfoMsgType (5)          // Request information about a specific event
#define  PMIFRequestFileInfoMsgType (6)           // Request information about a specific image file in a specific resolution type and crop
#define  PMIFRequestImageSliceMsgType (7)         // Request a specific slice from a specific image file
#define  PMIFRequestClearBufferMsgType (8)        // Clear image file buffer
#define  PMIFRequestShutDownMsgType (9)           // Request Shutdown

//   AMETHYST to PEARL
#define   PMIFAckMsgType ( 128)                   // Acknowledge reception of the message
#define   PMIFNAckMsgType (129)                   // Reason for not receiving the message 
#define   PMIFAnsStatusMsgType (130)              // Report status
#define   PMIFAnsEventInfoMsgType (131)           // Description of a specific event.
#define   PMIFAnsFileInfoMsgType (132)            // Description of a specific file in a specific event
#define   PMIFAnsImageSliceMsgType (133)          // Deliver a slice of an image file
#define   PMIFAnsParameterMsgType  (134)          // Report current value of a parameter
//
//PMIFRequestExtendedStatusMsgType=0, - Request status.
//
typedef  struct PMIFRequestStatusMsg 
{
  PMIFMsgHeaderT header;
  PMIFMsgFooterT footer;
} PMIFRequestStatusMsgT;
//
//PMIFRequestSetParameterMsgType=1, -Set parameters for the WEM operation
//
typedef  struct PMIFRequestSetParameterMsg 
{
  PMIFMsgHeaderT header;
  AMETHTimeT timeOfDay;
  uint8 numberOfParameters;	//Number of parameters in the message.
  AMETHPARPairT paramPairs[MAX_AMETHPAR_IN_MSG];
  PMIFMsgFooterT footer;
} PMIFRequestSetParameterMsgT;
//
//PMIFRequestGetParameterMsgType=2, -Get the value currently set to a parameter
//
typedef  struct PMIFRequestGetParameterMsg 
{
  PMIFMsgHeaderT header;
  uint8 numberOfParameters;	//Number of parameters in the message.
  AMETHPARId parId[MAX_AMETHPAR_IN_MSG];
  //array of  parameter enum  whose length is  numberOfParameters 
   PMIFMsgFooterT footer;
} PMIFRequestGetParameterMsgT;
//
//PMIFRequestHuntingModeMsgType=3,  -Request the Amethyst to start/stop hunting for movement using the current parameters
//
typedef  struct PMIFRequestHuntingModeMsg 
{
  PMIFMsgHeaderT header;
  AMETHStartStopE start;
  PMIFMsgFooterT footer;
} PMIFRequestHuntingModeMsgT;
//
//PMIFRequestImageCaptureMsgType=4, -Request the Amethyst to take a snapshot at requested time of day or a series of times using the current parameters
//
typedef  struct PMIFRequestImageCaptureMsg 
{
  PMIFMsgHeaderT header;
  AMETHYesNoE periodic;
  AMETHTimeT captureTimeOfDay; // 0xffffffffffffffff - indicates to capture an image immediatly
  uint16 numberOfRepetitions;
  uint32 deltaTimeMsec; //delta time in mili seconds
  PMIFMsgFooterT footer;
} PMIFRequestImageCaptureMsgT;
//
//PMIFRequestEventInfoMsgType=5,    -Request information about a specific event
//
typedef  struct PMIFRequestEventInfoMsg 
{
  PMIFMsgHeaderT header;
  AMETHTimeT eventTime;
} PMIFRequestEventInfoMsgT;

// PMIFRequestFileInfoMsgType=6,    -Request information about a specific image file in a specific resolution type and crop
typedef  struct PMIFRequestFileInfoMsg 
{
  PMIFMsgHeaderT header;
  uint16 eventNumber;
  AMETHTimeT eventTime;
} PMIFRequestFileInfoMsgT;



//PMIFRequestImageSliceMsgType=7,   -Request a specific slice from a specific image file

typedef  struct PMIFRequestImageSliceMsg 
{
  PMIFMsgHeaderT header;
  uint16 eventNumber;
  uint16 imageFileNumber; //FFFF to get the faivorite
  uint8 fileType;
  uint8 cropType;
  uint16 sliceNumber;
  PMIFMsgFooterT footer;
} PMIFRequestImageSliceMsgT;

//PMIFRequestClearBufferMsgType=8,  -Clear image file buffer  
typedef  struct PMIFRequestClearBufferMsg 
{
  PMIFMsgHeaderT header;
  AMETHYesNoE clearAll;
  AMETHTimeT eventTime;
  PMIFMsgFooterT footer;
} PMIFRequestClearBufferMsgT;
//
//PMIFRequestShutDownMsgType=9,  -Request shutdown 
typedef  struct PMIFRequestShutDownMsg 
{
  PMIFMsgHeaderT header;
  PMIFMsgFooterT footer;
} PMIFRequestShutDownMsgT;

//
//  AMETHYST to PEARL
//
//PMIFAckMsgType =128,                   -Acknowledge reception of the message
typedef  struct PMIFAnsAckMsg 
{
  PMIFMsgHeaderT header;
  uint16 ackedSequenceNumber;
  PMIFMsgTypeE ackedMessageType; //FFFF to get the faivorite
  PMIFMsgFooterT footer;
} PMIFAnsAckMsgT;

//PMIFNAckMsgType= 129,                  -Reason for not receiving the message 
typedef  struct PMIFAnsNackMsg 
{
  PMIFMsgHeaderT header;
  uint16 nackedSequenceNumber;
  PMIFMsgTypeE nackedMessageType; //FFFF to get the faivorite
  uint8 reason;
  PMIFMsgFooterT footer;
} PMIFAnsNackMsgT;
//PMIFAnsStatusMsgType = 130,    -Report status

typedef  struct PMIFAnsStatusMsg 
{
  PMIFMsgHeaderT header;
  AMETHTimeT timeOfDay;
  AMETHYesNoE isHunting;
  AMETHYesNoE isLastEventFinished;
  uint16 lastDetectedEventId;
  uint16 lastEventImageNumber;
  AMETHTimeT lastFavoriteTimeofDay;//In ""Most interesting" file in the last Event
  uint16 numOfSlicesInLastFavoriteFullImage; //number of slices in the full image file (not only the portion requested)of the most interesting file in the last event
  //Favorite's Trigger Coordinates 
  //( LU ,RB) coordinates of the frame surrounding the detected event (relative to a VGA sensor)
  AMETHPointT detectionFrameBounderiesUpperLeft; //	
  AMETHPointT detectionFrameBounderiesBottomRight;
  // Favorite's Trigger Center of Mass
  //( LU ,RB) coordinates of the frame surrounding the detected event (relative to a VGA sensor)
  AMETHPointT DetectionCenterOfMass;//	X, Y 
  uint16 lastSnapshotEventNumber;//If a snapshot was taken this field will hold the number of the event. If no snapshot was taken this field will be = FFFF
  uint16 lastSnapshotImageNumber; //If a snapshot was taken this field will hold the number of that image. If no snapshot was taken this field will be = FFFF
  AMETHTimeT lastSnapshotImageTimeOfDay;
  uint8 memoryUsagePrecentage; //Percentage of the usage SD card memory  0-100 %
  AMETHTimeT memoryFirstImageTimeOfDay;
  AMETHTimeT memoryLastImageTimeOfDay;
  uint8 numberOfNacksSentSinceLastStatus; //Number of NACKs sent since last status
  uint8 lastError; //enum of errors TBD
  uint16 secondsSinceLastErrorTime;   //in seconds
  PMIFMsgFooterT footer;
} PMIFAnsStatusMsgT;





//PMIFAnsEventInfoMsgType = 131,       -Description of a specific event.
typedef  struct PMIFAnsEventInfoMsg 
{//todo
  PMIFMsgHeaderT header;
  uint16 eventNumber;
  AMETHYesNoE isEventFinished;
  AMETHTimeT eventStartTimeOfDay;
  uint16 numberOfImagesInTheEvent;
  uint8  detectionQuality;   //it is not clear
  PMIFMsgFooterT footer;
} PMIFAnsEventInfoMsgT;

//PMIFAnsFileInfoMsgType = 132,        -Description of a specific file in a specific event
typedef  struct PMIFAnsFileInfoMsg 
{//todo
  PMIFMsgHeaderT header;
  uint16 eventNumber;
  uint16 imageFileNumber; //FFFF - to get the "favorite" image from the event
  AMETHFileFormatTypeE fileType;
  AMETHTimeT ImageFileTimeOfDay;
  uint16 numOfSlicesInImageFile;
  //Detection Coordinates (in type 1)
  AMETHPointT detectionFrameBounderiesUpperLeft; //	
  AMETHPointT detectionFrameBounderiesBottomRight;//
  uint8 imageQualityFactor; //	0-100%
  PMIFMsgFooterT footer;
} PMIFAnsFileInfoMsgT;

//PMIFAnsImageSliceMsgType =133,       -Deliver a slice of an image file
typedef  struct PMIFAnsImageSliceMsgDummy 
{
  PMIFMsgHeaderT header;
  AMETHFileFormatTypeE fileType;
  AMETHCropE cropType;
  uint8 frameSize;
  uint8 padding;
  uint16 eventNumber;
  uint16 imageFileNumber;  
  uint16 sliceNumber;
  uint16 totalslicesInFile;
//  uint8  payload[MAX_PAYLOAD_BYTES_LENGTH];
  PMIFMsgFooterT footer;
} PMIFAnsImageSliceMsgDummyT;


#define MAX_PAYLOAD_BYTES_LENGTH (MAX_PAIF_MESSAGE_SIZE-sizeof(PMIFAnsImageSliceMsgDummyT))


typedef  struct PMIFAnsImageSliceMsg 
{
  PMIFMsgHeaderT header;
  uint8 fileType;
  uint8 cropType;
  uint8 frameSize;
  uint8 padding;
  uint16 eventNumber;
  uint16 imageFileNumber;  
  uint16 sliceNumber;
  uint16 totalslicesInFile;
  uint8  payload[MAX_PAYLOAD_BYTES_LENGTH];
  PMIFMsgFooterT footer;
} PMIFAnsImageSliceMsgT;
 
   //FFFF to get the faivorite
  




//PMIFAnsParameterMsgType  =134,       -Report current value of a parameter
typedef  struct PMIFAnsParameterMsg 
{//todo
  PMIFMsgHeaderT header;
  PMIFMsgFooterT footer;
} PMIFAnsParameterMsgT;


//functions prototypes

PMIFMsgLengthT  AmethifBuildRequestImageSliceMsg(   uint8* buf);
PMIFMsgLengthT AmethifHandleMessage(uint8* buf ) ;
PMIFMsgLengthT  AmethifSendMessage(uint8 *buf, PMIFMsgLengthT dataLength);

#endif // AMETHYST_INTERFACE_H 

